package com.elong.android.specialhouse.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dp.android.elong.crash.LogWriter;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.adapter.MyOrderAdapter;
import com.elong.android.specialhouse.adapter.MyOrderAdapter.HouseOrderItemClickListener;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.base.DialogUtils;
import com.elong.android.specialhouse.entity.GetOrderListParam;
import com.elong.android.specialhouse.entity.HouseOrderEntity;
import com.elong.android.specialhouse.entity.response.OrderListResponse;
import com.elong.android.specialhouse.request.CancelOrderRequest;
import com.elong.android.specialhouse.request.ConfirmCheckInRequest;
import com.elong.android.specialhouse.request.DeleteOrderReq;
import com.elong.android.specialhouse.request.UrgeOrderResponse;
import com.elong.android.specialhouse.ui.SuperListView;
import com.elong.android.specialhouse.ui.SuperListView.OnLoadMoreListener;
import com.elong.android.specialhouse.ui.SuperListView.OnPullDownRefreshListener;
import com.elong.android.specialhouse.utils.EventReportTools;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.request.RequestOption;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;
import com.elong.payment.base.PaymentConstants;

import java.util.ArrayList;
import java.util.List;

//import com.elong.payment.base.PaymentConstants; TODO 支付相关

/**
 * @author yang.yu
 * @ClassName: MyOrderActivity
 * @Description: 订单页
 * @date 2015-8-19 上午10:52:14
 */
public class MyOrderActivity extends BaseVolleyActivity<IResponse<?>> implements
        OnItemClickListener, OnItemLongClickListener,
        ViewTreeObserver.OnPreDrawListener {
    private static final String PAGE_NAME = "youfangLodgerOrderPage";
    public static final int MODE_TENANT = 0;
    public static final int MODE_LANDLORD = 1;
    private int currentTabID;

    /* 处理中，房客订单列表展示（订单状态为：新单、接单成功） */
    public final static int LORDER_ORDER_STATUS_DOING = 4;
    /* 待入住，房客订单列表展示（订单状态为：预订成功） */
    public final static int LORDER_ORDER_STATUS_STAY_IN = 5;
    /* 待评价，房客订单列表展示（订单状态为：已入住、订单完成） */
    public final static int LORDER_ORDER_STATUS_COMMENT = 6;
    /* 待评价，房客订单列表展示（订单状态为：已入住、订单完成） */
    public final static int ORDER_STATUS_ALL = 7;

    public final static int LORDER_STATUS = 0;
    /* 默认传给服务器订单状态 */
    private int mOrderStatus = ORDER_STATUS_ALL;
    /* 全部,已入住,处理中,已确认,已取消,四个列表当前页的索引 */
    private int pageindexof_list_all = 1;
    private int pageindexof_list_being = 1;
    private int pageindexof_list_wait = 1;
    private int pageindexof_list_finish = 1;
    /* 每次请求的订单条数 */
    public static final int ORDER_COUNT_ONETIME = 20;
    private Context context;
    private LinearLayout llMyOrderView;
    private LinearLayout llEmptyHint;
    private Button btnLogin;
    private ImageView ivMessage;
    private TextView tvMyOrderAll;
    private TextView tvMyOrderBeing;
    private TextView tvMyOrderWait;
    private TextView tvMyOrderFinish;
    private TextView tvMyOrderNoResult;
    private SuperListView lvMyOrderAll;
    private SuperListView lvMyOrderBeing;
    private SuperListView lvMyOrderWait;
    private SuperListView lvMyOrderFinish;
    private MyOrderAdapter mAdapterAll;
    private MyOrderAdapter mAdapterBeing;
    private MyOrderAdapter mAdapterWait;
    private MyOrderAdapter mAdapterFinish;
    private List<HouseOrderEntity> mOrderListDataAll;
    private List<HouseOrderEntity> mOrderListDataBeing;
    private List<HouseOrderEntity> mOrderListDataWait;
    private List<HouseOrderEntity> mOrderListDataFinish;
    private long mUserId;
    private boolean isLogin;
    private String mCancelHint;
    private GetOrderListParam mOrderListParam = null;
    /**
     * 标志是否是删除订单操作
     */
    private boolean isDeleteOrder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventReportTools.sendPageOpenEvent(PAGE_NAME);
        getWindow().getDecorView().getViewTreeObserver()
                .addOnPreDrawListener(this);
        context = this;
        currentTabID = R.id.tv_my_order_all;
        onInitViews();
    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: onRequestData
     * @Description: 获取订单数据
     */
    private void onRequestData() {
        if (mOrderListParam == null) {
            mOrderListParam = new GetOrderListParam();
        }
        mOrderListParam.UserType = LORDER_STATUS;
        mOrderListParam.userid = mUserId;
        mOrderListParam.TagType = 3;
        mOrderListParam.PageSize = ORDER_COUNT_ONETIME;
        getOrderList(mOrderListParam, mOrderStatus, pageindexof_list_all);
    }

    /**
     * @param @param param
     * @param @param orderStatusAll 订单类型
     * @param @param pageindex 页数
     * @return void
     * @throws
     * @Title: getOrderList
     * @Description: TODO 获取订单数据
     */
    private void getOrderList(GetOrderListParam param, int orderStatusAll,
                              int pageindex) {
        param.orderStatus = orderStatusAll;
        param.PageNo = pageindex;
        RequestOption requestOption = new RequestOption();
        JSONObject params = (JSONObject) JSON.toJSON(param);
        requestOption.setJsonParam(params);
        requestHttp(requestOption, ApartmentAPI.getOrderList, StringResponse.class, true);
    }

    /**
     * @param @param param
     * @param @param orderStatusAll 订单类型
     * @param @param pageindex 页数
     * @param @param isShowDialog 是否显示对话框
     * @return void
     * @throws
     * @Title: getOrderList
     * @Description: TODO 获取订单数据
     */
    private void getOrderList(GetOrderListParam param, int orderStatusAll, int pageindex, boolean isShowDialog) {
        param.orderStatus = orderStatusAll;
        param.PageNo = pageindex;
        RequestOption requestOption = new RequestOption();
        JSONObject params = (JSONObject) JSON.toJSON(param);
        requestOption.setJsonParam(params);
        requestHttp(requestOption, ApartmentAPI.getOrderList, StringResponse.class, isShowDialog);
    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: onInitViews
     * @Description: 初始化View
     */
    private void onInitViews() {
        llMyOrderView = (LinearLayout) findViewById(R.id.ll_my_order_view);
        llEmptyHint = (LinearLayout) findViewById(R.id.ll_empty_hint);
        btnLogin = (Button) findViewById(R.id.btn_login);
        tvMyOrderAll = (TextView) findViewById(R.id.tv_my_order_all);
        tvMyOrderBeing = (TextView) findViewById(R.id.tv_my_order_being);
        tvMyOrderWait = (TextView) findViewById(R.id.tv_my_order_wait);
        tvMyOrderFinish = (TextView) findViewById(R.id.tv_my_order_finish);
        lvMyOrderAll = (SuperListView) findViewById(R.id.lv_my_order_all);
        lvMyOrderBeing = (SuperListView) findViewById(R.id.lv_my_order_being);
        lvMyOrderWait = (SuperListView) findViewById(R.id.lv_my_order_wait);
        lvMyOrderFinish = (SuperListView) findViewById(R.id.lv_my_order_finish);
        tvMyOrderNoResult = (TextView) findViewById(R.id.tv_my_order_noresult);
        findViewById(R.id.common_head_back).setVisibility(View.GONE);
        ivMessage = (ImageView) findViewById(R.id.common_message);
        ivMessage.setVisibility(View.VISIBLE);
        tvMyOrderAll.setSelected(true);
        mOrderListDataAll = new ArrayList<HouseOrderEntity>();
        mOrderListDataBeing = new ArrayList<HouseOrderEntity>();
        mOrderListDataWait = new ArrayList<HouseOrderEntity>();
        mOrderListDataFinish = new ArrayList<HouseOrderEntity>();
        mAdapterAll = new MyOrderAdapter(context, mOrderListDataAll);
        mAdapterBeing = new MyOrderAdapter(context, mOrderListDataBeing);
        mAdapterWait = new MyOrderAdapter(context, mOrderListDataWait);
        mAdapterFinish = new MyOrderAdapter(context, mOrderListDataFinish);
        mAdapterAll.setHouseOrderItemClickListener(orderclicklistener);
        mAdapterBeing.setHouseOrderItemClickListener(orderclicklistener);
        mAdapterWait.setHouseOrderItemClickListener(orderclicklistener);
        mAdapterFinish.setHouseOrderItemClickListener(orderclicklistener);
        lvMyOrderAll.setOnItemClickListener(this);
        lvMyOrderBeing.setOnItemClickListener(this);
        lvMyOrderWait.setOnItemClickListener(this);
        lvMyOrderFinish.setOnItemClickListener(this);
        lvMyOrderAll.setOnItemLongClickListener(this);
        lvMyOrderBeing.setOnItemLongClickListener(this);
        lvMyOrderWait.setOnItemLongClickListener(this);
        lvMyOrderFinish.setOnItemLongClickListener(this);
        lvMyOrderAll.setAdapter(mAdapterAll);
        lvMyOrderBeing.setAdapter(mAdapterBeing);
        lvMyOrderWait.setAdapter(mAdapterWait);
        lvMyOrderFinish.setAdapter(mAdapterFinish);
        addListener();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        startOrderDetailActivity(position, id);
    }

    HouseOrderEntity item;

    private void startOrderDetailActivity(int position, long id) {
        switch (mOrderStatus) {
            case ORDER_STATUS_ALL:
                item = mAdapterAll.getData().get(position - 1);
                break;
            case LORDER_ORDER_STATUS_DOING:
                item = mAdapterBeing.getData().get(position - 1);
                break;
            case LORDER_ORDER_STATUS_STAY_IN:
                item = mAdapterWait.getData().get(position - 1);
                break;
            case LORDER_ORDER_STATUS_COMMENT:
                item = mAdapterFinish.getData().get(position - 1);
                break;
            default:
                break;
        }

        Intent intent = new Intent(MyOrderActivity.this,
                MyOrderDetailActivity.class);
        intent.putExtra("mGorderId", item.GorderId);
        startActivity(intent);

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
                                   final int position, final long id) {
        DialogUtils.showConfirmDialog(context, null, getString(R.string.delete_order),
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        if (isWindowLocked()) {
                            return;
                        }
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            requestDeleteOrder(position);
                        }
                    }
                });
        return true;
    }

    private void requestDeleteOrder(int position) {
        DeleteOrderReq req = new DeleteOrderReq();
        req.UserType = Account.getInstance().currentIsCustomer() ? MODE_TENANT : MODE_LANDLORD;
        req.UserId = Long.valueOf(Account.getInstance().getUserId());
        switch (mOrderStatus) {
            case ORDER_STATUS_ALL:
                item = mAdapterAll.getData().get(position - 1);
                break;
            case LORDER_ORDER_STATUS_DOING:
                item = mAdapterBeing.getData().get(position - 1);
                break;
            case LORDER_ORDER_STATUS_STAY_IN:
                item = mAdapterWait.getData().get(position - 1);
                break;
            case LORDER_ORDER_STATUS_COMMENT:
                item = mAdapterFinish.getData().get(position - 1);
                break;
            default:
                break;
        }
        req.orderId = item.getOrderId();
        requestHttp(req, ApartmentAPI.deleteOrder, true);
        isDeleteOrder = true;
    }

    private void addListener() {
        btnLogin.setOnClickListener(this);
        tvMyOrderAll.setOnClickListener(tabClickListener);
        tvMyOrderBeing.setOnClickListener(tabClickListener);
        tvMyOrderWait.setOnClickListener(tabClickListener);
        tvMyOrderFinish.setOnClickListener(tabClickListener);

        // 为"全部订单列表"设置下拉刷新监听
        lvMyOrderAll.setOnRefreshListener(new OnPullDownRefreshListener() {

            @Override
            public void onRefresh() {
                pageindexof_list_all = 1;
                getOrderList(mOrderListParam, ORDER_STATUS_ALL,
                        pageindexof_list_all);
            }
        });
        // 为"全部订单列表"设置加载更多监听
        lvMyOrderAll.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore() {
                getOrderList(mOrderListParam, ORDER_STATUS_ALL,
                        pageindexof_list_all);
            }
        });
        // 为"处理中订单列表"设置下拉刷新监听
        lvMyOrderBeing.setOnRefreshListener(new OnPullDownRefreshListener() {

            @Override
            public void onRefresh() {
                pageindexof_list_being = 1;
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_DOING,
                        pageindexof_list_being);
            }
        });
        // 为"处理中订单列表"设置加载更多监听
        lvMyOrderBeing.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore() {
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_DOING,
                        pageindexof_list_being);
            }
        });
        // 为"待入住订单列表"设置下拉刷新监听
        lvMyOrderWait.setOnRefreshListener(new OnPullDownRefreshListener() {

            @Override
            public void onRefresh() {
                pageindexof_list_wait = 1;
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_STAY_IN,
                        pageindexof_list_wait);
            }
        });
        // 为"待入住订单列表"设置加载更多监听
        lvMyOrderWait.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore() {
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_STAY_IN,
                        pageindexof_list_wait);
            }
        });
        // 为"已结算订单列表"设置下拉刷新监听
        lvMyOrderFinish.setOnRefreshListener(new OnPullDownRefreshListener() {

            @Override
            public void onRefresh() {
                pageindexof_list_finish = 1;
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_COMMENT,
                        pageindexof_list_finish);
            }
        });
        // 为"已结算订单列表"设置加载更多监听
        lvMyOrderFinish.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore() {
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_COMMENT,
                        pageindexof_list_finish);
            }
        });

    }

    OnClickListener tabClickListener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            int id = view.getId();
            tvMyOrderNoResult.setVisibility(View.GONE);
            if (currentTabID != id) {
                switch (currentTabID) {
                    case R.id.tv_my_order_all:
                        lvMyOrderAll.setVisibility(View.GONE);
                        break;
                    case R.id.tv_my_order_being:
                        lvMyOrderBeing.setVisibility(View.GONE);
                        break;
                    case R.id.tv_my_order_wait:
                        lvMyOrderWait.setVisibility(View.GONE);
                        break;
                    case R.id.tv_my_order_finish:
                        lvMyOrderFinish.setVisibility(View.GONE);
                        break;
                }
                switch (id) {
                    case R.id.tv_my_order_all:
                        mOrderStatus = ORDER_STATUS_ALL;
                        lvMyOrderAll.setVisibility(View.VISIBLE);
                        if (mOrderListDataAll == null || mOrderListDataAll.size() == 0) {
                            getOrderList(mOrderListParam, mOrderStatus, 1);
                        }
                        break;
                    case R.id.tv_my_order_being:
                        mOrderStatus = LORDER_ORDER_STATUS_DOING;
                        lvMyOrderBeing.setVisibility(View.VISIBLE);
                        if (mOrderListDataBeing == null || mOrderListDataBeing.size() == 0) {
                            getOrderList(mOrderListParam, mOrderStatus, 1);
                        }
                        break;
                    case R.id.tv_my_order_wait:
                        mOrderStatus = LORDER_ORDER_STATUS_STAY_IN;
                        lvMyOrderWait.setVisibility(View.VISIBLE);
                        if (mOrderListDataWait == null || mOrderListDataWait.size() == 0) {
                            getOrderList(mOrderListParam, mOrderStatus, 1);
                        }
                        break;
                    case R.id.tv_my_order_finish:
                        mOrderStatus = LORDER_ORDER_STATUS_COMMENT;
                        lvMyOrderFinish.setVisibility(View.VISIBLE);
                        if (mOrderListDataFinish == null || mOrderListDataFinish.size() == 0) {
                            getOrderList(mOrderListParam, mOrderStatus, 1);
                        }
                        break;
                }
                findViewById(currentTabID).setSelected(false);
                currentTabID = id;
                view.setSelected(true);
            }
        }

    };

    @Override
    protected void initContentView() {
        setContentView(R.layout.act_my_order);
        setHeader(R.string.order);
    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        if (t == null) {
            return;
        }
        JSONObject result = null;
        try {
            result = (JSONObject) JSONObject.parse(((StringResponse) t)
                    .getContent());
        } catch (Exception e) {
            LogWriter.logException(TAG, "", e);
            e.printStackTrace();
            return;
        }
        if (handleIsError(request, result)) {
            return;
        }
        switch (((ApartmentAPI) request.getRequestOption().getHusky())) {
            case getOrderList:
                switch (mOrderStatus) {
                    case ORDER_STATUS_ALL:
                        refreshAllList(lvMyOrderAll, mAdapterAll, mOrderListDataAll, result);
                        break;
                    case LORDER_ORDER_STATUS_DOING:
                        refreshBeingList(lvMyOrderBeing, mAdapterBeing, mOrderListDataBeing, result);
                        break;
                    case LORDER_ORDER_STATUS_STAY_IN:
                        refreshWaitList(lvMyOrderWait, mAdapterWait, mOrderListDataWait, result);
                        break;
                    case LORDER_ORDER_STATUS_COMMENT:
                        refreshFinishList(lvMyOrderFinish, mAdapterFinish, mOrderListDataFinish, result);
                        break;
                    default:
                        break;
                }
                if (isDeleteOrder) {
                    isDeleteOrder = false;
                    DialogUtils.showToast(this, getString(R.string.delete_order_succeed), true);
                }
                break;
            case deleteOrder:
                getOrderList(mOrderListParam, mOrderStatus, 1, false);
                clearData();
                break;
            case orderCancel:
                refreshAllOrderState();
                DialogUtils.showToast(this, getString(R.string.cancel_order_succeed), true);
                break;
            case confirmCheckIn:
                refreshAllOrderState();
                break;
            case orderUrge:
                DialogUtils.showToast(this, getString(R.string.reminder_order), true);
                break;
            case acceptOrder:
                refreshAllOrderState();
                DialogUtils.showToast(this, getString(R.string.accept_order), true);
                break;
            case refuseOrder:
                refreshAllOrderState();
                DialogUtils.showToast(this, getString(R.string.refuse_order), true);
                break;
        }
    }

    private void clearData() {
        mOrderListDataAll.clear();
        mOrderListDataBeing.clear();
        mOrderListDataWait.clear();
        mOrderListDataFinish.clear();
        mAdapterAll.notifyDataSetChanged();
        mAdapterBeing.notifyDataSetChanged();
        mAdapterWait.notifyDataSetChanged();
        mAdapterFinish.notifyDataSetChanged();
        pageindexof_list_all = 1;
        pageindexof_list_being = 1;
        pageindexof_list_wait = 1;
        pageindexof_list_finish = 1;
    }

    /**
     * 当有改变订单状态的操作时,发送刷新页面请求Tab回到全部订单
     */
    private void refreshAllOrderState() {
        tvMyOrderAll.performClick();
        mOrderListDataAll.clear();
        mOrderListDataBeing.clear();
        mOrderListDataWait.clear();
        mOrderListDataFinish.clear();
        mAdapterAll.notifyDataSetChanged();
        mAdapterBeing.notifyDataSetChanged();
        mAdapterWait.notifyDataSetChanged();
        mAdapterFinish.notifyDataSetChanged();
        pageindexof_list_all = 1;
        pageindexof_list_being = 1;
        pageindexof_list_wait = 1;
        pageindexof_list_finish = 1;
        getOrderList(mOrderListParam, ORDER_STATUS_ALL, pageindexof_list_all);
    }

    private void refreshFinishList(SuperListView listview,
                                   MyOrderAdapter adapter, List<HouseOrderEntity> adapterdata,
                                   Object response) {
        OrderListResponse entity = (OrderListResponse) JSON.parseObject(
                response.toString(), OrderListResponse.class);
        List<HouseOrderEntity> orders = entity.getList();
        if (null == orders) {
            orders = new ArrayList<HouseOrderEntity>();
        }
        int count = orders.size();
        if (pageindexof_list_finish == 1) {
            listview.onRefreshComplete();
            adapterdata.clear();
        } else {
            listview.onLoadMoreComplete();
        }
        adapter.setData(orders, pageindexof_list_finish == 1 ? false : true);
        if (count < ORDER_COUNT_ONETIME) {
            listview.setLastPage();
            if (pageindexof_list_finish == 1 && orders.size() == 0) {
                lvMyOrderFinish.setVisibility(View.GONE);
                showNoRestultView(true, LORDER_ORDER_STATUS_COMMENT);
                return;
            }
            fillCurrentTabList(currentTabID);
        } else {
            pageindexof_list_finish = pageindexof_list_finish + 1;
            if (adapter.getCount() < (ORDER_COUNT_ONETIME / 2)) {
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_COMMENT,
                        pageindexof_list_finish);
            } else {
                fillCurrentTabList(currentTabID);
            }
            listview.cancelLastPage();
        }
    }

    private void refreshWaitList(SuperListView listview,
                                 MyOrderAdapter adapter, List<HouseOrderEntity> adapterdata,
                                 Object response) {
        OrderListResponse entity = (OrderListResponse) JSON.parseObject(
                response.toString(), OrderListResponse.class);
        List<HouseOrderEntity> orders = entity.getList();
        if (null == orders) {
            orders = new ArrayList<HouseOrderEntity>();
        }
        int count = orders.size();
        if (pageindexof_list_wait == 1) {
            listview.onRefreshComplete();
            adapterdata.clear();
        } else {
            listview.onLoadMoreComplete();
        }
        adapter.setData(orders, pageindexof_list_wait == 1 ? false : true);
        if (count < ORDER_COUNT_ONETIME) {
            listview.setLastPage();
            if (pageindexof_list_wait == 1 && orders.size() == 0) {
                lvMyOrderWait.setVisibility(View.GONE);
                showNoRestultView(true, LORDER_ORDER_STATUS_STAY_IN);
                return;
            }
            fillCurrentTabList(currentTabID);
        } else {
            pageindexof_list_wait = pageindexof_list_wait + 1;
            if (adapter.getCount() < (ORDER_COUNT_ONETIME / 2)) {
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_STAY_IN,
                        pageindexof_list_wait);
            } else {
                fillCurrentTabList(currentTabID);
            }
            listview.cancelLastPage();
        }
    }

    private void refreshBeingList(SuperListView listview,
                                  MyOrderAdapter adapter, List<HouseOrderEntity> adapterdata,
                                  Object response) {
        OrderListResponse entity = (OrderListResponse) JSON.parseObject(
                response.toString(), OrderListResponse.class);
        List<HouseOrderEntity> orders = entity.getList();
        if (null == orders) {
            orders = new ArrayList<HouseOrderEntity>();
        }
        int count = orders.size();
        if (pageindexof_list_being == 1) {
            listview.onRefreshComplete();
            adapterdata.clear();
        } else {
            listview.onLoadMoreComplete();
        }
        adapter.setData(orders, pageindexof_list_being == 1 ? false : true);
        if (count < ORDER_COUNT_ONETIME) {
            listview.setLastPage();
            if (pageindexof_list_being == 1 && orders.size() == 0) {
                lvMyOrderBeing.setVisibility(View.GONE);
                showNoRestultView(true, LORDER_ORDER_STATUS_DOING);
                return;
            }
            fillCurrentTabList(currentTabID);
        } else {
            pageindexof_list_being = pageindexof_list_being + 1;
            if (adapter.getCount() < (ORDER_COUNT_ONETIME / 2)) {
                getOrderList(mOrderListParam, LORDER_ORDER_STATUS_DOING,
                        pageindexof_list_being);
            } else {
                fillCurrentTabList(currentTabID);
            }
            listview.cancelLastPage();
        }
    }

    private void refreshAllList(SuperListView listview, MyOrderAdapter adapter, List<HouseOrderEntity> adapterdata,
                                Object response) {
        OrderListResponse entity = (OrderListResponse) JSON.parseObject(
                response.toString(), OrderListResponse.class);
        List<HouseOrderEntity> orders = entity.getList();
        if (null == orders) {
            orders = new ArrayList<HouseOrderEntity>();
        }
        int count = orders.size();
        if (pageindexof_list_all == 1) {
            listview.onRefreshComplete();
            adapterdata.clear();
        } else {
            listview.onLoadMoreComplete();
        }
        adapter.setData(orders, pageindexof_list_all == 1 ? false : true);
        if (count < ORDER_COUNT_ONETIME) {
            listview.setLastPage();
            if (pageindexof_list_all == 1 && orders.size() == 0) {
                lvMyOrderAll.setVisibility(View.GONE);
                showNoRestultView(true, ORDER_STATUS_ALL);
                return;
            }
            fillCurrentTabList(currentTabID);
        } else {
            pageindexof_list_all = pageindexof_list_all + 1;
            if (adapter.getCount() < (ORDER_COUNT_ONETIME / 2)) {
                getOrderList(mOrderListParam, ORDER_STATUS_ALL,
                        pageindexof_list_all);
            } else {
                fillCurrentTabList(currentTabID);
            }
            listview.cancelLastPage();
        }
    }

    /**
     * @param @param isshow
     * @param @param ordertype
     * @return void
     * @throws
     * @Title: showNoRestultView
     * @Description: TODO 显示无结果信息
     */
    private void showNoRestultView(boolean isshow, int ordertype) {
        try {
            tvMyOrderNoResult.setVisibility(isshow ? View.VISIBLE : View.GONE);
            tvMyOrderNoResult.setText(getResources().getStringArray(
                    R.array.order_noresults)[ordertype - 1]);
        } catch (Exception e) {
            LogWriter.logException(TAG, "", e);
        }
    }

    private HouseOrderItemClickListener orderclicklistener = new HouseOrderItemClickListener() {

        @Override
        public void onClick_cancel(final HouseOrderEntity order) {
            EventReportTools.sendPageSpotEvent(PAGE_NAME,"cancel");//取消订单cancel
            if (StringUtils.isNotEmpty(order.getCancelPromptNote())) {
                mCancelHint = getResources().getString(R.string.cancel_rules);
            } else {
                mCancelHint = getResources().getString(
                        R.string.order_cancel_hint);
            }
            DialogUtils.showConfirmDialog(context, mCancelHint,
                    order.getCancelPromptNote(),
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            if (isWindowLocked()) {
                                return;
                            }
                            if (which == DialogInterface.BUTTON_POSITIVE) {
                                cancelOrder(order);
                            }
                        }
                    });
        }

        @Override
        public void onClick_to_pay(HouseOrderEntity order) {
            EventReportTools.sendPageSpotEvent(PAGE_NAME,"pay");//去支付pay
            toPayOrder(order);
        }

        @Override
        public void onClick_to_comment(HouseOrderEntity order) {
            EventReportTools.sendPageSpotEvent(PAGE_NAME,"evaluate");//去评价evaluate
            Intent intent = new Intent(MyOrderActivity.this, PublishEvaluationActivity.class);
            intent.putExtra(AppConstants.ORDER_ID, order.getOrderId());
            intent.putExtra(AppConstants.GORDER_ID, order.getGorderId());
            intent.putExtra(AppConstants.HOUSE_ID, order.getApartmentId());
            intent.putExtra(AppConstants.HOUSE_IAMGE_URL,
                    order.getHouseImageUrl());
            intent.putExtra(AppConstants.APARTMENT_NAME,
                    order.getApartmentName());
            intent.putExtra(AppConstants.CHECKIN_DATE_TIME,
                    order.getArriveDate());
            intent.putExtra(AppConstants.CHECKOUT_DATE_TIME,
                    order.getLeaveDate());
            startActivity(intent);
        }

        @Override
        public void onClick_confirm(HouseOrderEntity order) {
            confirmCheckIn(order);
        }

        @Override
        public void onClick_reminder(HouseOrderEntity order) {
            reminderOrder(order);
        }

        @Override
        public void onClick_contact_he(HouseOrderEntity order) {
            Intent intent = new Intent(MyOrderActivity.this, ChatActivity.class);
            intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_ID,
                    order.getLodgerId());
            intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_NAME,
                    order.getLodgerName());
            startActivity(intent);
        }

    };

    private void fillCurrentTabList(int currentTab) {
        switch (currentTab) {
            case R.id.tv_my_order_all:
                mOrderStatus = ORDER_STATUS_ALL;
                lvMyOrderAll.setVisibility(View.VISIBLE);
                if (mOrderListDataAll == null || mOrderListDataAll.size() == 0) {
                    getOrderList(mOrderListParam, mOrderStatus, 1);
                }
                break;
            case R.id.tv_my_order_being:
                mOrderStatus = LORDER_ORDER_STATUS_DOING;
                lvMyOrderBeing.setVisibility(View.VISIBLE);
                if (mOrderListDataBeing == null || mOrderListDataBeing.size() == 0) {
                    getOrderList(mOrderListParam, mOrderStatus, 1);
                }
                break;
            case R.id.tv_my_order_wait:
                mOrderStatus = LORDER_ORDER_STATUS_STAY_IN;
                lvMyOrderWait.setVisibility(View.VISIBLE);
                if (mOrderListDataWait == null || mOrderListDataWait.size() == 0) {
                    getOrderList(mOrderListParam, mOrderStatus, 1);
                }
                break;
            case R.id.tv_my_order_finish:
                mOrderStatus = LORDER_ORDER_STATUS_COMMENT;
                lvMyOrderFinish.setVisibility(View.VISIBLE);
                if (mOrderListDataFinish == null
                        || mOrderListDataFinish.size() == 0) {
                    getOrderList(mOrderListParam, mOrderStatus, 1);
                }
                break;
        }
    }

    /**
     * @param @param order
     * @return void
     * @throws
     * @Title: reminderOrder
     * @Description: TODO 催单
     */
    protected void reminderOrder(HouseOrderEntity order) {
        UrgeOrderResponse req = new UrgeOrderResponse();
        req.gorderId = order.getGorderId();
        requestHttp(req, ApartmentAPI.orderUrge, StringResponse.class, true);
    }

    /**
     * @param @param order
     * @return void
     * @throws
     * @Title: confirmCheckIn
     * @Description: TODO 确认入住
     */
    protected void confirmCheckIn(HouseOrderEntity order) {
        ConfirmCheckInRequest req = new ConfirmCheckInRequest();
        req.orderId = order.getOrderId();
        requestHttp(req, ApartmentAPI.confirmCheckIn, StringResponse.class,
                true);
    }

    /**
     * @param @param order
     * @return void
     * @throws
     * @Title: toPayOrder
     * @Description: 去支付, 跳到预定已提交页统一处理
     */
    protected void toPayOrder(HouseOrderEntity order) {
//    	TODO 去支付功能
        Intent intent = new Intent(this, BookingSubmitedActivity.class);
        intent.putExtra(PaymentConstants.orderId, order.getOrderId());
        intent.putExtra(PaymentConstants.gorderId, order.getGorderId());
        intent.putExtra(PaymentConstants.totalPrice,
                Double.valueOf(order.getGorderAmount()));
        intent.putExtra(PaymentConstants.hotelName, order.ApartmentName);
        intent.putExtra(PaymentConstants.isCanback, false);
        String checkinDate = order.getArriveDate();
        String checkoutDate = order.getLeaveDate();
//        if (!TextUtils.isEmpty(checkinDate)) {
//            intent.putExtra(PaymentConstants.checkinDate, checkinDate);
//        }
//        if (!TextUtils.isEmpty(checkoutDate)) {
//            intent.putExtra(PaymentConstants.checkoutDate, checkoutDate);
//        }
//        int totalDays = DateTimeUtils.getIntervalDays(checkinDate,
//                checkoutDate, "yyyy-MM-dd");
//        intent.putExtra(PaymentConstants.totalsDays, totalDays + "");
        // 标识是继续支付，即不是从预定完成后直接去支付，而是从订单列表或者详情页中去支付的
        intent.putExtra(AppConstants.KEY_IS_CONTINUE_PAY, true);
        startActivity(intent);
    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: cancelOrder
     * @Description: TODO 取消订单
     */
    protected void cancelOrder(HouseOrderEntity order) {
        CancelOrderRequest req = new CancelOrderRequest();
        req.UserId = mUserId;
        req.OrderId = order.getOrderId();
        requestHttp(req, ApartmentAPI.orderCancel, StringResponse.class, true);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.common_message:
                break;
            case R.id.btn_login:
                startActivity(new Intent(MyOrderActivity.this, LoginActivity.class));
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int getReceiverPriority() {
        return AppConstants.RECEIVER_PRIORITY_HOME;
    }

    @Override
    public boolean onPreDraw() {
        if (isLogin != Account.getInstance().isLogin()) {
            isLogin = Account.getInstance().isLogin();
            refreshUI();
        }
        return true;
    }

    private void refreshUI() {
        if (Account.getInstance().isLogin()) {
            mUserId = Long.parseLong(Account.getInstance().getUserId());
            if (mAdapterAll != null) {
                mOrderListDataAll.clear();
                mOrderListDataBeing.clear();
                mOrderListDataWait.clear();
                mOrderListDataFinish.clear();
                mAdapterAll.notifyDataSetChanged();
                mAdapterBeing.notifyDataSetChanged();
                mAdapterWait.notifyDataSetChanged();
                mAdapterFinish.notifyDataSetChanged();
                pageindexof_list_all = 1;
                pageindexof_list_being = 1;
                pageindexof_list_wait = 1;
                pageindexof_list_finish = 1;
            }
            onRequestData();
            llEmptyHint.setVisibility(View.GONE);
            llMyOrderView.setVisibility(View.VISIBLE);
        } else {
            llEmptyHint.setVisibility(View.VISIBLE);
            llMyOrderView.setVisibility(View.GONE);
        }
    }

}
